package top.boking.E10.resuful.update;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @version: V1.0
 * @Description: e-Builder openApi Demo
 * @description: 泛微协同商务系统, 版权所有.
 */
public class UpdateDemo {
    private static final String URL = "http://127.0.0.1:18090";
    private static final String URL_DEV = "https://weapp.yunteams.cn";
    private static final String URL_RELEASE = "https://weapp.mulinquan.cn/";
    private static final String ETEAMSID = "PCACCOUNT_bc0fca0732bf3666c7ce8bc7d1fe7896";
    private static final String USER= "5116064451991577795";
    private static final String USER_RELEASE= "3086018350865928585";

    private static final String PK= "g2c39b";

    public static void main(String[] args) {
        UpdateDemo saveDemo = new UpdateDemo();
        String result = saveDemo.doAction(ETEAMSID);
        System.out.println(result);
    }
    public static JSONObject getMainTable() {
        JSONObject main = new JSONObject();
        main.put("id",887910121128296458L);
        main.put("887150646550446080","shxlchang");
        return main;
    }

    /**
     * e-Builder openApi Demo
     * ex:getFormDataList
     * @param accessToken
     */
    public String doAction(String accessToken) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(URL+"/api/ebuilder/form/formdata/updateFormData/"+PK+"?ETEAMSID=" + ETEAMSID);
        JSONObject params = new JSONObject();
        JSONObject paramDatajson = new JSONObject();

        //header
        JSONObject header = new JSONObject();
        String operator = "5112849484828049659";
        header.put("operator", USER_RELEASE);
        paramDatajson.put("header", header);



        //mainTable
        JSONObject mainTable = getMainTable();
        //operationinfo
        JSONObject operationinfo = new JSONObject();
        operationinfo.put("optionNoFindIgnore",false);
        //datas
        JSONArray datas = new JSONArray();
        JSONObject data = new JSONObject();
        data.put("operationinfo",operationinfo);
        data.put("mainTable",mainTable);
        datas.add(data);
        paramDatajson.put("datas",datas);

        params.put("datajson", paramDatajson);

        System.out.println("===request datajson===" + paramDatajson);

        List nvps = new ArrayList();
        if (params != null) {
            for (Map.Entry entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair((String) entry.getKey(), JSONObject.toJSONString(entry.getValue())));
            }
        }
        try {
            UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(nvps, "utf-8");
            httpPost.setEntity(reqEntity);
            // exec post request.
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    System.out.println("request failed");
                    throw new RuntimeException("request failed");
                } else {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        System.out.println("request success");
                        return EntityUtils.toString(entity, Charset.forName("UTF-8"));
                    }
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";

    }





    /**
     * send request
     *
     * @param url
     * @param reqParam
     * @return
     * @throws Exception
     */
    public static String post(String url, Map<Object,Map.Entry> reqParam) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // create httppost.
            HttpPost httppost = new HttpPost(url);
            httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            List nvps = new ArrayList();
            if (reqParam != null) {
                for (Map.Entry entry : reqParam.entrySet()) {
                    nvps.add(new BasicNameValuePair((String) entry.getKey(), (String) entry.getValue()));
                }
            }
            UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(nvps, "utf-8");
            httppost.setEntity(reqEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    throw new RuntimeException("request failed");
                } else {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        return EntityUtils.toString(entity, Charset.forName("UTF-8"));
                    }
                }
            } finally {
                response.close();
            }
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String getFormatDate() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd HH:mm:ss");
        return simpleDateFormat.format(new Date());
    }
    public static String null2String(Object s) {
        return s == null ? "" : s.toString();
    }

}
